from py2neo import Graph,Node,Relationship,NodeMatcher,RelationshipMatcher
import json

def connectNeo4j(ip,username,password):
    graph = Graph(ip,name=username,password=password)
    matcher = NodeMatcher(graph)
    rmatcher = RelationshipMatcher(graph)
    
    return graph,matcher,rmatcher

def init_nodes(nodes):
    for node in nodes:
        print(node)
        '''print(node['fid'])

        print(node['path'])'''
        fid = str(node['fid'])

        path = node['path']
        filename = "temp"

        if(path == "<built-in>" or path == "<scratch space>"):
            filename = path
        else:
            temp = path.split("/")
            filename = temp[len(temp)-1]
        #print(filename)

        #new_node = Node(package_name,ac_label,ac_label_index,name=node_name)
        label = "file_function"
        new_node = Node(label,filename=filename,funfid=fid,path=path)######changehere!!!
        #filedic[fid] = new_node
        graph.create(new_node)
    return


def init_include(data_include):
    for data in data_include:
        print(data)
        src = str(data['startnode'])
        dst = str(data['endnode'])

        nodesrc = matcher.match(funfid=src).first()######changehere!!!
        nodedst = matcher.match(funfid=dst).first()######changehere!!!

        includelabel = "function_tse"

        newrelation_symbol2ref = Relationship(nodesrc,includelabel,nodedst)

        graph.create(newrelation_symbol2ref)

if __name__ == "__main__":
    (graph,matcher,rmatcher) = connectNeo4j('http://localhost:7474',"neo4j","123456")

    data_node = json.load(open("filenode.json","r"))
    init_nodes(data_node)
    
    data_include = json.load(open("functionedge_internal.json","r"))
    init_include(data_include)
